import Taro from '@tarojs/taro'
import { action, observable } from 'mobx'

// apis
import * as productsInfoApi from '../../apis/productsInfoApi'
import * as productsColumnApi from '../../apis/productsColumnApi'
import * as productCategoryApi from '../../apis/productCategoryApi'

// models
// import ProductsColumn from '../../models/ProductsColumn'
import ProductsInfo from '../../models/ProductsInfo'
import ProductsCategory from '../../models/ProductsCategory'

class ProductListStore {
  @observable
  isInit: boolean = false

  @observable
  topImgs: string[] = []

  @observable
  productsColumnId: number

  // @observable
  // productsColumn: ProductsColumn

  @observable
  productCategorys: ProductsCategory[] = []

  @observable
  currentCategoryId?: number

  @observable
  products: ProductsInfo[] = []

  @observable
  isLoadingProducts: boolean = true

  @action
  async navigateTo(params: { productsColumnId: number }) {
    Taro.navigateTo({
      url: `/pages/productList/index?productsColumnId=${params.productsColumnId}`,
    })
  }

  async init(params: { productsColumnId: number }) {
    Taro.showLoading({ title: '加载中...' })
    this.isInit = false
    this.currentCategoryId = undefined
    this.productCategorys = []
    this.products = []
    this.productsColumnId = params.productsColumnId

    // await this.loadProductsColumn(params.productsColumnId)

    // 加载分类
    await this.loadCategorys()
    if (this.productCategorys && this.productCategorys[0]) {
      this.currentCategoryId = this.productCategorys[0].id
    }

    Taro.hideLoading()

    // 加载商品
    await this.loadProducts()

    this.topImgs = [...Array(10)].map(_ => {
      return 'https://free.com.tw/blog/wp-content/uploads/2014/08/Placekitten480-g.jpg'
    })
    this.isInit = true
  }

  // @action
  // async loadProductsColumn(productsColumnId: number) {
  //   const { data: productsColumn } = await productsColumnApi.queryById({ id: productsColumnId })

  //   this.productsColumn = productsColumn
  // }

  /**
   * 加载分类
   */
  @action
  async loadCategorys() {
    const resp = await productCategoryApi.getListByColumnId({ columnId: this.productsColumnId })
    this.productCategorys = resp.data
  }

  /**
   * 加载商品
   */
  @action
  async loadProducts() {
    if (!this.currentCategoryId) return
    this.isLoadingProducts = true
    const resp = await productsInfoApi.getByCategoryId({ categoryId: this.currentCategoryId, page: 1, limit: 10 })

    this.products = resp.data
    this.isLoadingProducts = false
  }

  @action
  changeCategory = async (category: ProductsCategory) => {
    this.currentCategoryId = category.id
    this.products = []
    this.loadProducts()
  }
}

export default new ProductListStore()
